package com.zkq.graduate.schedule;

import com.zkq.graduate.pojo.StudentWithReport;
import com.zkq.graduate.service.MongoDbService;
import com.zkq.graduate.util.FileUtil;
import com.zkq.graduate.util.LocalDateTimeUtil;
import com.zkq.graduate.util.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.io.File;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author zhangkaiqiang
 * @Date 2019/12/19  9:34
 * @Description TODO
 *
 * 定时执行:每一个小时执行一次,检测保存临时文件的文件夹下的文件修改时间大于10分钟,
 * 进行保存到mongodb,并删除本地文件的操作
 */
@Slf4j
@Configuration
@EnableScheduling
@EnableAsync
public class DeleteAndUploadFileScheduleTask{

	
	@Value("${create.openFilePath}")
	private String openFilePath;

	@Value("${create.paperFilePath}")
	private String paperFilePath;

	@Value("${uploadAndDeleteFile.timeCell}")
	private long timeCell;


	@Resource(name = "mongoService")
	private MongoDbService mongoDbService;

	/**
	 * 定时上传更新开题报告
	 */
	@Scheduled(cron = "${uploadAndDeleteFile.cron}")
	@Async
	public void updateAndDeleteOpen(){
		log.info(LocalDateTimeUtil.getStringNow()+">>>>>>开题报告定时任务开始执行>>>>>>,操作路径为:"+openFilePath);
		uploadFileToMongo(openFilePath);
		log.info(LocalDateTimeUtil.getStringNow()+">>>>>>开题报告定时任务执行完毕");
	}


	/**
	 * 定时上传毕业论文并删除本地文件
	 */
	@Scheduled(cron = "${uploadAndDeleteFile.cron}")
	@Async
	public void updateAndDeletePaper(){
		log.info(LocalDateTimeUtil.getStringNow()+">>>>>>>>毕业论文定时任务开始执行,操作路径为:"+paperFilePath);
		uploadFileToMongo(paperFilePath);
		log.info(LocalDateTimeUtil.getStringNow()+">>>>>>>>毕业论文定时任务执行完毕");
	}


	/**
	 * 真正执行的定时任务方法
	 */
	private void uploadFileToMongo(String filePath){
		if(StringUtils.isNotBlank(filePath)){
			File file=new File(filePath);
			if(!file.isDirectory()){
				throw new IllegalArgumentException(filePath+"is not an directory");
			}

			File[] files=file.listFiles();
			if(files!=null && files.length!=0){
				// 遍历判断文件的修改时间是否大于10分钟
				for(File tempFile:files){
					long previousUpdateMillions=tempFile.lastModified();
					long betweenTime= LocalDateTimeUtil.getBetweenTimeToSecond(LocalDateTimeUtil.timestampToLocalDateTime(previousUpdateMillions),LocalDateTime.now());
					String fileName=tempFile.getName();
					System.out.println(betweenTime);
					if(betweenTime>timeCell){
						// 进行mongodb中文件内容的替换并更改状态位审核中
						byte[] fileContext= FileUtil.getFileByte(tempFile);
						String mds= MD5Util.mD5Encode(new String(fileContext));
						Map<String,Object> updateCondition=new HashMap<>();
						updateCondition.put("fileName",fileName);
						StudentWithReport studentWithReport=StudentWithReport.builder()
								.fileContext(fileContext)
								.isLast(true)
								.md5(mds)
								.status("已审核")
								.build();
						int result=0;
						// 跟新开题报告还是毕业论文区分
						if(FileUtil.fileType(fileName)==1){
							result=mongoDbService.updateFileByAddition(updateCondition,studentWithReport,"open");
						} else if(FileUtil.fileType(fileName)==2){
							result=mongoDbService.updateFileByAddition(updateCondition,studentWithReport,"paper");
						}
						log.info("定时任务,文件更新到MongoDB,文件为:>>>>>>"+fileName);
						if(1==result){
							tempFile.delete();
							log.info("定时任务,文件上传MongoDB后,删除文件,文件为:>>>>>>"+fileName);
						}
					} else {
						log.info(fileName+"上次修改时间距离当前时间小于"+timeCell+"秒,不进行更新到mongodb操作");
					}
				}
			}
		}
	}
}